package com.framework.dubbo.producer.file2html;

import cn.hutool.core.util.StrUtil;
import com.framework.dubbo.producer.config.Constants;
import org.apache.poi.POIXMLDocumentPart;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 基于回调的实现文档预览
 * 本地存储图片和base64转码
 * @author xianggj
 * @Date 2021/6/7 14:13
 **/
public class ExcelFilePreviewer extends AbstractFilePreviewTools {

    public ExcelFilePreviewer() {
    }

    @Override
    public String convert2Html(String path) {
        return readExcelToHtml(path);
    }

    @Override
    public String convert2Html(InputStream in, String ext) {
        return readExcelToHtml(in, true);
    }

    @Override
    public String convert2Str(InputStream in, String ext) {
        return readExcelToHtml(in, false);
    }


    /**
     * 总宽度标签 标签不重复
     */
    private  final String TABLE_WIDTH = "#$#table-width-value#$#";

    /**
     * 文件类型标记
     */
    private static final String XLSX_TAG = "xlsx";

    private static final String XLS_TAG = "xls";


    /**
     * 程序入口方法（将指定路径的excel文件读取成字符串）
     * @param filePath 文件的路径
     * @return <table>...</table> 字符串
     */
    public String readExcelToHtml(String filePath){
        String htmlExcel = null;
        try (InputStream is = new FileInputStream(new File(filePath))) {
            htmlExcel = readExcelToHtml(is, true);
        } catch (Exception e) {
            e.printStackTrace();
            htmlExcel = String.format("文件[%s]不存在", filePath);
        }
        return htmlExcel;
    }
    /**
     * 程序入口方法（将指定路径的excel文件读取成字符串）
     * @param is excel转换成的输入流
     * @return <table>...</table> 字符串
     */
    public String readExcelToHtml(InputStream is, boolean isHtml){
        String result = null;
        try {
            Workbook wb = WorkbookFactory.create(is);
            if(isHtml) {
                result = readWorkbook(wb);
            } else {
                result = readWorkbookStr(wb);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = "excel文件读取失败";
        }finally{
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 根据excel的版本分配不同的读取方法进行处理
     * @param wb wb
     * @return
     */
    private String readWorkbookStr(Workbook wb){
        int numberOfSheets = wb.getNumberOfSheets();
        StringBuffer sb = new StringBuffer();
        String fileType = null;
        if (wb instanceof XSSFWorkbook) {
            fileType = XLSX_TAG;
        }else if(wb instanceof HSSFWorkbook){
            fileType = XLS_TAG;
        } else {
            throw new RuntimeException("当前格式文件不支持！");
        }
        for (int i = 0; i < numberOfSheets; i++) {
            Sheet currentSheet = wb.getSheetAt(i);
            String name = wb.getSheetName(i);
            sb.append(name);
            sb.append(Constants.ENTER);
            String str = parsingExcel2Str(currentSheet, fileType);
            sb.append(str);
            sb.append(Constants.ENTER);
        }
        return sb.toString();
    }

    /**
     * 转excel为html
     * @param sheet 当前页签
     * @param fileType 文件类型标识
     * @return
     */
    public String parsingExcel2Str(Sheet sheet, String fileType){
        StringBuffer sb = new StringBuffer();
        int maxLastColNum = getColsOfTable(sheet)[0];//最大行号默认值
        for (int rowNum = sheet.getFirstRowNum(); rowNum <= sheet.getLastRowNum(); rowNum ++) {
            //列太多 不进行处理
            if(rowNum > 1000) {
                break;
            }
            int lastColNum = maxLastColNum;

            Row row = sheet.getRow(rowNum);
            if (null != row) {
                lastColNum = row.getLastCellNum();
            }
            if (null == row) {
                continue;
            }
            for (int colNum = 0; colNum < lastColNum; colNum ++) {
                Cell cell = row.getCell(colNum);
                if(cell != null) {
                    sb.append(getCellValue(cell));
                    sb.append(Constants.WITHE_SPACE);
                }
            }
            sb.append(Constants.ENTER);
        }
        return sb.toString();
    }

    /**
     * 根据excel的版本分配不同的读取方法进行处理
     * @param wb wb
     * @return
     */
    private String readWorkbook(Workbook wb){
        int numberOfSheets = wb.getNumberOfSheets();
        StringBuffer sb = new StringBuffer();
        sb.append("<html>");
        sb.append("<head>");
        sb.append("<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />");
        sb.append("</head>");
        sb.append("<body text='#000000'>");
        String fileType = null;
        if (wb instanceof XSSFWorkbook) {
            fileType = XLSX_TAG;
        }else if(wb instanceof HSSFWorkbook){
            fileType = XLS_TAG;
        } else {
            throw new RuntimeException("当前格式文件不支持！");
        }
        for (int i = 0; i < numberOfSheets; i++) {
            Sheet currentSheet = wb.getSheetAt(i);
            String name = wb.getSheetName(i);
            sb.append("<h2>"+name+"</h2>");
            sb.append("<hr/><br/>");
            String html = parsingExcel2Html(currentSheet, fileType);
            sb.append(html);
            sb.append("<br/><br/>");
        }
        sb.append("</body>");
        sb.append("</html>");
        return sb.toString();
    }

    /**
     * 转excel为html
     * @param sheet 当前页签
     * @param fileType 文件类型标识
     * @return
     */
    public String parsingExcel2Html(Sheet sheet, String fileType){
        StringBuffer sb = new StringBuffer();
        //1.缓存储excel图片 key为行号+“-”+列号
        Map<String, PictureData> sheetIndexPicMap = new HashMap<>();
        String sheetName = sheet.getSheetName();
        try {
            sheetIndexPicMap = getSheetPictrues(sheet, fileType);
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("缓存图片失败");
        }

        //2.记录合并单元格信息
        Map[] maps = getRowSpanColSpanMap(sheet);
        //3.读取excel拼装html
        sb.append("<table style='border-collapse:collapse;/*table-layout:fixed;word-break:break-all;*/width:"+TABLE_WIDTH+";'>");
        int maxLastColNum = getColsOfTable(sheet)[0];//最大行号默认值
        int maxRowHeight = getColsOfTable(sheet)[1];//行高默认值
        float tableWidth = 0;

        for (int rowNum = sheet.getFirstRowNum(); rowNum <= sheet.getLastRowNum(); rowNum ++) {
            //列太多 不进行处理
            if(rowNum > 1000) {
                break;
            }
            int lastColNum = maxLastColNum;
            int rowHeight = maxRowHeight;

            Row row = sheet.getRow(rowNum);
            if (null != row) {
                rowHeight = row.getHeight();
                lastColNum = row.getLastCellNum();
            }
            if (null == row) {
                if (sheet.getLastRowNum() == 0 && sheetIndexPicMap.size() > 0){//纯图excel
                    createImgHtml(sb, sheetIndexPicMap, sheetName);
                }else {
                    sb.append("<tr><td>  </td></tr>");
                }
                continue;
            }else if(row.getZeroHeight()){
                continue;
            }else if(0 == rowHeight){
                continue;     //针对jxl的隐藏行（此类隐藏行只是把高度设置为0，单getZeroHeight无法识别）
            }
            float width = addTrHtml(sheet, fileType, sb, sheetIndexPicMap,
                    sheetName, maps, rowNum, lastColNum, rowHeight, row);
            tableWidth = Math.max(tableWidth, width);
            continue;
        }
        sb.append("</table>");
        String tableWidthStr = tableWidth == 0?"100%":tableWidth+"pt";
        return StrUtil.replace(sb.toString(), TABLE_WIDTH, tableWidthStr);
    }

    /**
     * 添加行
     * @param sheet
     * @param fileType
     * @param sb
     * @param sheetIndexPicMap
     * @param sheetName
     * @param maps
     * @param rowNum
     * @param lastColNum
     * @param rowHeight
     * @param row
     * @return
     */
    private  float addTrHtml(Sheet sheet, String fileType,
                             StringBuffer sb, Map<String, PictureData> sheetIndexPicMap,
                             String sheetName,
                             Map[] maps,
                             int rowNum,
                             int lastColNum,
                             int rowHeight,
                             Row row) {
        //计算行高
        float hight = (row.getHeightInPoints() / 72) * 96;
        sb.append("<tr height='"+ String.format("%1.2f", hight)+"pt'>");
        float tableWidth = 0;
        for (int colNum = 0; colNum < lastColNum; colNum ++) {
            //隐藏单元格
            if(sheet.isColumnHidden(colNum)){
                continue;
            }

            Cell cell = row.getCell(colNum);
            if (cell == null){ //空白单元格
                //没得样式 会导致页面看上去很不适应 直接去前面的一格的样式就可以了
                String s = sb.toString();
                if (s.contains(" style='")){
                    String style = StrUtil.subBefore(StrUtil.subAfter(s, " style='", true), "'", false);
                    sb.append("<td style='" + style + "'>");
                } else {
                    sb.append("<td>");
                }
                //空白单元格有可能有图片
               addImgHtml(sb, sheetIndexPicMap, sheetName, rowNum, rowHeight, colNum);

                sb.append("</td>");
                continue;
            }
            //获取单元格的值
            String stringValue = getCellValue(cell);
            String key = rowNum + "," + colNum;
            if (maps[0].containsKey(key)) {
                String pointString = (String)maps[0].get(key);
                String[] split = pointString.split(",");
                int bottomeRow = Integer.valueOf(split[0]);
                int bottomeCol = Integer.valueOf(split[1]);
                int rowSpan = bottomeRow - rowNum + 1;
                int colSpan = bottomeCol - colNum + 1;
                if(maps[2].containsKey(key)){
                    Object o = maps[2].get(key);
                    rowSpan = rowSpan - (Integer) o;
                }
                sb.append("<td rowspan= '" + rowSpan + "' colspan= '"+ colSpan + "' ");
                if(maps.length > 3 && maps[3].containsKey(key)){
                    //此类数据首行被隐藏，value为空，需使用其他方式获取值
                    stringValue = getMergedRegionValue(sheet, rowNum, colNum);
                }
            } else if (maps[1].containsKey(key)) {
                maps[1].remove(key);
                continue;
            } else {
                sb.append("<td ");
            }
            //添加样式
            float cellWidth = dealExcelStyle(fileType, sheet, cell, maps, sb);//处理单元格样式
            tableWidth += cellWidth;
            sb.append(">");
            addImgHtml(sb, sheetIndexPicMap, sheetName, rowNum, rowHeight, colNum);
            if (StrUtil.isBlank(stringValue)) {
                sb.append("   ");
            } else {
                // 将ascii码为160的空格转换为html下的空格（ ）
                sb.append(stringValue
                        .replace(String.valueOf((char) 160)," ")
                        .replace("\n", "<br/>")
                        .replace("\t", "&emsp;")
                        .replace(" ", "&nbsp;")
                );
            }
            sb.append("</td>");
        }
        sb.append("</tr>");
        return tableWidth;
    }

    /**
     * 添加单元格图片
     * @param sb
     * @param sheetIndexPicMap
     * @param sheetName
     * @param rowNum
     * @param rowHeight
     * @param colNum
     */
    private  void addImgHtml(StringBuffer sb, Map<String, PictureData> sheetIndexPicMap,
                             String sheetName, int rowNum, int rowHeight, int colNum) {
        String imageRowNum =  rowNum + "-" + colNum;
        if(sheetIndexPicMap.containsKey(imageRowNum)){
            PictureData pictureData = sheetIndexPicMap.get(imageRowNum);
            String ext = pictureData.suggestFileExtension();
//            String fileName = sheetName + "-" + imageRowNum + "." + ext;
            byte[] data = pictureData.getData();
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
            String imagePath = writeToLocal(byteArrayInputStream, ext);
            String imageHtml = "<img src='" + imagePath + "' style='height:" + rowHeight / 20 + "px;'>";
            sb.append(imageHtml);
        }
    }

    /**
     * 纯图片创建
     * @param sb
     * @param sheetIndexPicMap
     * @param sheetName
     */
    private  void createImgHtml(StringBuffer sb, Map<String, PictureData> sheetIndexPicMap,
                                String sheetName) {
        Set<String> keys = sheetIndexPicMap.keySet();
        List<String> keylist = keys.stream().sorted((a, b) -> {
            String[] splita = StrUtil.split(a, "-");
            String[] splitb = StrUtil.split(b, "-");
            if (splita[0].equals(splitb[0])){
                return Integer.valueOf(splita[1]) - Integer.valueOf(splitb[1]);
            }
            return Integer.valueOf(splita[0]) - Integer.valueOf(splitb[0]);
        }).collect(Collectors.toList());
        for (String key: keylist) {
            PictureData pictureData = sheetIndexPicMap.get(key);
            String ext = pictureData.suggestFileExtension();
            byte[] data = pictureData.getData();
            int[] widthAndHight = getwidthAndHightByImageBytes(data);
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
            String imagePath = writeToLocal(byteArrayInputStream, ext);
            String imageHtml = "<img src='" + imagePath + "' style='height:"+widthAndHight[1]+"px;'>";
            sb.append("<tr><td > "+imageHtml+"</td></tr>");
        }
    }

    /**
     * 获取图片原始宽高
     * @param data
     * @return
     */
    private  int[] getwidthAndHightByImageBytes(byte[] data ){
        try {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
            BufferedImage sourceImg = ImageIO.read(byteArrayInputStream);
            return new int[]{sourceImg.getWidth(), sourceImg.getHeight()};
        } catch (IOException e) {
            e.printStackTrace();
            return new int[]{300, 200};
        }
    }

    /**
     * 分析excel表格，记录合并单元格相关的参数，用于之后html页面元素的合并操作
     * @param sheet
     * @return
     */
    private  Map[] getRowSpanColSpanMap(Sheet sheet) {
        Map<String, String> map0 = new HashMap<>();	//保存合并单元格的对应起始和截止单元格
        Map<String, String> map1 = new HashMap<>();	//保存被合并的那些单元格
        Map<String, Integer> map2 = new HashMap<>();	//记录被隐藏的单元格个数
        Map<String, String> map3 = new HashMap<>();	//记录合并了单元格，但是合并的首行被隐藏的情况
        int mergedNum = sheet.getNumMergedRegions();
        CellRangeAddress range = null;
        Row row = null;
        for (int i = 0; i < mergedNum; i++) {
            range = sheet.getMergedRegion(i);
            int topRow = range.getFirstRow();
            int topCol = range.getFirstColumn();
            int bottomRow = range.getLastRow();
            int bottomCol = range.getLastColumn();
            /**
             * 此类数据为合并了单元格的数据
             * 1.处理隐藏（只处理行隐藏，列隐藏poi已经处理）
             */
            if(topRow != bottomRow){
                int zeroRoleNum = 0;
                int tempRow = topRow;
                for(int j = topRow; j <= bottomRow; j ++){
                    row = sheet.getRow(j);
                    if(row.getZeroHeight() || row.getHeight() == 0){
                        if(j == tempRow){
                            //首行就进行隐藏，将rowTop向后移
                            tempRow ++;
                            continue;//由于top下移，后面计算rowSpan时会扣除移走的列，所以不必增加zeroRoleNum;
                        }
                        zeroRoleNum ++;
                    }
                }
                if(tempRow != topRow){
                    map3.put(tempRow + "," + topCol,topRow + "," + topCol);
                    topRow = tempRow;
                }
                if (zeroRoleNum!=0){
                    map2.put(topRow + "," + topCol, zeroRoleNum);
                }
            }
            map0.put(topRow + "," + topCol, bottomRow + "," + bottomCol);
            int tempRow = topRow;
            while (tempRow <= bottomRow) {
                int tempCol = topCol;
                while (tempCol <= bottomCol) {
                    map1.put(tempRow + "," + tempCol, topRow + "," + topCol);
                    tempCol++;
                }
                tempRow++;
            }
            map1.remove(topRow + "," + topCol);
        }
        Map[] map = { map0, map1 ,map2,map3};
        return map;
    }


    /**
     * 获取合并单元格的值
     * @param sheet
     * @param row
     * @param column
     * @return
     */
    public String getMergedRegionValue(Sheet sheet, int row, int column){
        int sheetMergeCount = sheet.getNumMergedRegions();
        for(int i = 0 ; i < sheetMergeCount ; i++){
            CellRangeAddress ca = sheet.getMergedRegion(i);
            int firstColumn = ca.getFirstColumn();
            int lastColumn = ca.getLastColumn();
            int firstRow = ca.getFirstRow();
            int lastRow = ca.getLastRow();

            if(row >= firstRow && row <= lastRow){

                if(column >= firstColumn && column <= lastColumn){
                    Row fRow = sheet.getRow(firstRow);
                    Cell fCell = fRow.getCell(firstColumn);

                    return getCellValue(fCell) ;
                }
            }
        }
        return null ;
    }

    /**
     * 获取表格单元格Cell内容
     * @param cell
     * @return
     */
    private String getCellValue(Cell cell) {
        String result = null;
        switch (cell.getCellType()) {

            case Cell.CELL_TYPE_NUMERIC:// 数字类型

                //excel 中 没规定align的情况下 数值类型和时间类型靠右
                CellStyle style = cell.getCellStyle();
                short alignment = style.getAlignment();
                if (alignment != CellStyle.ALIGN_LEFT && alignment != CellStyle.ALIGN_CENTER){
                    style.setAlignment(CellStyle.ALIGN_RIGHT);
                }

                if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
                    SimpleDateFormat sdf = null;
                    if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
                        sdf = new SimpleDateFormat("HH:mm");
                    } else {// 日期
                        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    }
                    Date date = cell.getDateCellValue();
                    result = sdf.format(date);
                } else if (cell.getCellStyle().getDataFormat() == 58) {
                    // 处理自定义日期格式：m月d日(通过判断单元格的格式id解决，id的值是58)
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    double value = cell.getNumericCellValue();
                    Date date = DateUtil
                            .getJavaDate(value);
                    result = sdf.format(date);
                } else {
                    double value = cell.getNumericCellValue();
                    DecimalFormat format = new DecimalFormat();
                    String temp = style.getDataFormatString();
                    // 单元格设置成常规
                    if (temp.equals("General")) {
                        format.applyPattern("#.##");
                    } else if (temp.equals("0%")){//百分比
                        format = new DecimalFormat(temp);
                    }
                    result = format.format(value);
                }
                break;
            case Cell.CELL_TYPE_STRING:// String类型
                result = cell.getRichStringCellValue().toString();
                break;
            default:
                result = "";
                break;
        }
        return result;
    }

    /**
     * 处理表格样式
     * @param fileType 文件类型
     * @param sheet 当前页
     * @param cell 当前格
     * @param maps 合并信息
     * @return
     */
    private  float dealExcelStyle(String fileType, Sheet sheet, Cell cell, Map[] maps, StringBuffer sb){
        CellStyle cellStyle = cell.getCellStyle();
        float tableWidth = 0;
        if (cellStyle != null) {
            sb.append("align='" + convertAlignToHtml(cellStyle.getAlignment()) + "' ");//单元格内容的水平对齐方式
            sb.append("valign='"+ convertVerticalAlignToHtml(cellStyle.getVerticalAlignment())+ "' ");//单元格中内容的垂直排列方式
            if (XLSX_TAG.equals(fileType)) {
                XSSFFont xf = ((XSSFCellStyle) cellStyle).getFont();
                short boldWeight = xf.getBoldweight();
                String fontName = xf.getFontName();
                sb.append("style='");
                sb.append("font-weight:" + boldWeight + ";"); // 字体加粗
//                sb.append("font-size: " + xf.getFontHeight() / 2 + "%;"); // 字体大小
                sb.append("font-size: " + xf.getFontHeightInPoints() + "pt;"); // 字体大小
                sb.append("font-family: " + fontName + ";"); // 字体类型
                int topRow = cell.getRowIndex();
                int topColumn = cell.getColumnIndex();
                String key = topRow + "," + topColumn;
                if(maps[0].containsKey(key)){//该单元格为合并单元格，宽度需要获取所有单元格宽度后合并
                    String value = (String)maps[0].get(key);
                    String[] ary = value.split(",");
                    int bottomColumn = Integer.parseInt(ary[1]);
                    if(topColumn != bottomColumn){//合并列，需要计算相应宽度
                        float columnWidth = 0;
                        for(int i = topColumn; i <= bottomColumn; i++){
                            columnWidth += sheet.getColumnWidthInPixels(i);
                        }
                        sb.append("width:" + String.format("%1.2f", columnWidth) + "pt;");
                        tableWidth += columnWidth;
                    }else{
                        float columnWidth = sheet.getColumnWidthInPixels(cell.getColumnIndex()) ;
                        sb.append("width:" + String.format("%1.2f", columnWidth) + "pt;");
                        tableWidth += columnWidth;
                    }
                }else{
                    float columnWidth = sheet.getColumnWidthInPixels(cell.getColumnIndex()) ;
                    sb.append("width:" + String.format("%1.2f", columnWidth) + "pt;");
                    tableWidth += columnWidth;
                }

                XSSFColor xc = xf.getXSSFColor();
                if (xc != null && !"".equals(xc.toString())) {
                    byte[] rgbWithTint = xc.getRgbWithTint();
                    String rgba = getColorStr2(rgbWithTint);
                    if (rgba != null){
                        sb.append("color:rgba(" + rgba + ");"); // 背景颜色
                    }
                }
                Color color = cellStyle.getFillForegroundColorColor();
                XSSFColor bgColor = (XSSFColor) color;
                if (bgColor != null && !"".equals(bgColor.toString())) {
                    byte[] rgbWithTint = bgColor.getRgbWithTint();
                    String rgba = getColorStr2(rgbWithTint);
                    if (rgba != null) {
                        sb.append("background-color:rgba(" + rgba + ");"); // 背景颜色
                    }
                }
                sb.append("border:solid #000000 1px;");
                //获取边框颜色
                sb.append(getBorderStyle(0,cellStyle.getBorderTop(), ((XSSFCellStyle) cellStyle).getTopBorderXSSFColor()));
                sb.append(getBorderStyle(1,cellStyle.getBorderRight(), ((XSSFCellStyle) cellStyle).getRightBorderXSSFColor()));
                sb.append(getBorderStyle(2,cellStyle.getBorderBottom(), ((XSSFCellStyle) cellStyle).getBottomBorderXSSFColor()));
                sb.append(getBorderStyle(3,cellStyle.getBorderLeft(), ((XSSFCellStyle) cellStyle).getLeftBorderXSSFColor()));
            }else if(XLS_TAG.equals(fileType)){
                Workbook wb = sheet.getWorkbook();
                HSSFFont hf = ((HSSFCellStyle) cellStyle).getFont(wb);
                short boldWeight = hf.getBoldweight();
                short fontColor = hf.getColor();
                sb.append("style='");

                HSSFPalette palette = ((HSSFWorkbook) wb).getCustomPalette(); // 类HSSFPalette用于求的颜色的国际标准形式
                HSSFColor hc = palette.getColor(fontColor);
                sb.append("font-weight:" + boldWeight + ";"); // 字体加粗
                sb.append("font-size: " + hf.getFontHeightInPoints() + "pt;"); // 字体大小
                sb.append("font-family: " + hf.getFontName() + ";"); // 字体类型
                String fontColorStr = convertToStardColor(hc);
                if (fontColorStr != null && !"".equals(fontColorStr.trim())) {
                    sb.append("color:" + fontColorStr + ";"); // 字体颜色
                }

                int topRow = cell.getRowIndex(),topColumn = cell.getColumnIndex();
                if(maps[0].containsKey(topRow + "," + topColumn)){//该单元格为合并单元格，宽度需要获取所有单元格宽度后合并
                    String value = (String)maps[0].get(topRow + "," + topColumn);
                    String[] ary = value.split(",");
                    int bottomColumn = Integer.parseInt(ary[1]);
                    if(topColumn != bottomColumn){//合并列，需要计算相应宽度
                        float columnWidth = 0;
                        for(int i = topColumn; i <= bottomColumn; i++){
                            columnWidth += sheet.getColumnWidthInPixels(i);
                        }
                        sb.append("width:" + String.format("%1.2f", columnWidth) + "pt;");
                        tableWidth += columnWidth;
                    }else{
                        float columnWidth = sheet.getColumnWidthInPixels(cell.getColumnIndex()) ;
                        sb.append("width:" + String.format("%1.2f", columnWidth)+ "pt;");
                        tableWidth += columnWidth;
                    }
                }else{
                    float columnWidth = sheet.getColumnWidthInPixels(cell.getColumnIndex()) ;
                    sb.append("width:" + String.format("%1.2f", columnWidth) + "pt;");
                    tableWidth += columnWidth;
                }

                short bgColor = cellStyle.getFillForegroundColor();
                hc = palette.getColor(bgColor);
                String bgColorStr = convertToStardColor(hc);
                if (bgColorStr != null && !"".equals(bgColorStr.trim())) {
                    sb.append("background-color:" + bgColorStr + ";"); 		// 背景颜色
                }
                sb.append("border:solid #000000 1px;");
            }
            sb.append("' ");

        }
        return tableWidth;
    }

    /**
     * 获取标准颜色
     * @param bgColor
     * @return
     */
    private StringBuffer getColorStr(XSSFColor bgColor) {
        double tint = bgColor.getTint();
        tint = (double) Math.round((1-tint)*100)/100;
        StringBuffer rgba = new StringBuffer();
        byte[] rgb = bgColor.getRgb();
        for (int i = 0; i < rgb.length ; i++) {
            int i1 = rgb[i];
            if (i1 < 0){
                i1 = 255 + i1;
            }
            rgba.append(i1);
            rgba.append(",");
        }
        rgba.append(tint);
        return rgba;
    }

    /**
     * 获取标准颜色
     * @return
     */
    private String getColorStr2(byte[] rgb) {
        StringBuffer rgba = new StringBuffer();
        if (rgb == null){
            return null;
        }
        for (int i = 0; i < rgb.length ; i++) {
            int i1 = rgb[i];
            if (i1 < 0){
                i1 = 255 + i1;
            }
            rgba.append(i1);
            rgba.append(",");
        }
        rgba.append(1);
        return rgba.toString();
    }

    /**
     * 单元格内容的水平对齐方式
     * @param alignment
     * @return
     */
    private String convertAlignToHtml(short alignment) {
        String align = "left";
        switch (alignment) {
            case CellStyle.ALIGN_LEFT:
                align = "left";
                break;
            case CellStyle.ALIGN_CENTER:
                align = "center";
                break;
            case CellStyle.ALIGN_RIGHT:
                align = "right";
                break;
            default:
                break;
        }
        return align;
    }

    /**
     * 单元格中内容的垂直排列方式
     * @param verticalAlignment
     * @return
     */
    private String convertVerticalAlignToHtml(short verticalAlignment) {
        String valign = "middle";
        switch (verticalAlignment) {
            case CellStyle.VERTICAL_BOTTOM:
                valign = "bottom";
                break;
            case CellStyle.VERTICAL_CENTER:
                valign = "center";
                break;
            case CellStyle.VERTICAL_TOP:
                valign = "top";
                break;
            default:
                break;
        }
        return valign;
    }

    private String convertToStardColor(HSSFColor hc) {
        StringBuffer sb = new StringBuffer("");
        if (hc != null) {
            if (HSSFColor.AUTOMATIC.index == hc.getIndex()) {
                return null;
            }
            sb.append("#");
            for (int i = 0; i < hc.getTriplet().length; i ++) {
                sb.append(fillWithZero(Integer.toHexString(hc.getTriplet()[i])));
            }
        }
        return sb.toString();
    }

    private String fillWithZero(String str) {
        if (str != null && str.length() < 2) {
            return "0" + str;
        }
        return str;
    }

     String[] bordesr = {"border-top:", "border-right:", "border-bottom:", "border-left:"};
     String[] borderStyles = {"solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid", "solid", "solid", "solid", "solid"};

    @SuppressWarnings("unused")
    private String getBorderStyle(HSSFPalette palette , int b, short s, short t){
        if(s == 0) {
            return  bordesr[b] + borderStyles[s] + "#d0d7e5 1px;";
        }
        String borderColorStr = convertToStardColor( palette.getColor(t));
        borderColorStr = borderColorStr == null || borderColorStr.length() < 1 ? "#000000" : borderColorStr;
        return bordesr[b] + borderStyles[s] + borderColorStr + " 1px;";
    }

    @SuppressWarnings("unused")
    private String getBorderStyle(int b, short s, XSSFColor xc){
        if(s == 0){
            return  bordesr[b] + borderStyles[s] + "#d0d7e5 1px;";
        }
        if (xc != null && ! "".equals(xc)) {
            String borderColorStr = xc.getARGBHex();//t.getARGBHex();
            borderColorStr=borderColorStr == null || borderColorStr.length() < 1 ? "#000000" : borderColorStr.substring(2);
            return bordesr[b] + borderStyles[s]+borderColorStr+" 1px;";
        }
        return "";
    }

    @SuppressWarnings("unused")
    private  void writeFile(String content, String path) {
        OutputStream os = null;
        BufferedWriter bw = null;
        try {
            File file = new File(path);
            os = new FileOutputStream(file);
            bw = new BufferedWriter(new OutputStreamWriter(os,"GBK"));
            bw.write(content);
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (null != bw) {
                    bw.close();
                }
                if (null != os) {
                    os.close();
                }
            } catch (IOException ie) {
                ie.printStackTrace();
            }
        }
    }


    /**
     * 获取Excel图片公共方法
     * @param sheet 当前sheet对象
     * @param fileType 文件类型
     * @return Map key:图片单元格索引（0_1_1）String，value:图片流PictureData
     */
    public Map<String, PictureData> getSheetPictrues(Sheet sheet, String fileType) throws IOException {
        if(XLS_TAG.equals(fileType)){
            return getPicturesByXls((HSSFSheet)sheet);
        }else if(XLSX_TAG.equals(fileType)){
            return getPicturesByXlsx((XSSFSheet) sheet);
        }else{
            return new HashMap<>();
        }
    }

    /**
     * 获取图片和位置 (xls)
     * @param sheet
     * @return
     * @throws IOException
     */
    public Map<String, PictureData> getPicturesByXls(HSSFSheet sheet) throws IOException {
        Map<String, PictureData> map = new HashMap<>();
        HSSFPatriarch drawingPatriarch = sheet.getDrawingPatriarch();
        if (drawingPatriarch == null){
            return map;
        }
        List<HSSFShape> list = drawingPatriarch.getChildren();
        for (HSSFShape shape : list) {
            if (shape instanceof HSSFPicture) {
                HSSFPicture picture = (HSSFPicture) shape;
                HSSFClientAnchor cAnchor = (HSSFClientAnchor) picture.getAnchor();
                String key = cAnchor.getRow1() + "-" + cAnchor.getCol1(); // 行号-列号
                PictureData pdata = picture.getPictureData();
                map.put(key, pdata);
            }
        }
        return map;
    }

    /**
     * 获取图片和位置 (xlsx)
     * @param sheet
     * @return
     * @throws IOException
     */
    public Map<String, PictureData> getPicturesByXlsx(XSSFSheet sheet) throws IOException {
        Map<String, PictureData> map = new HashMap<>();
        List<POIXMLDocumentPart> list = sheet.getRelations();
        for (POIXMLDocumentPart part : list) {
            if (part instanceof XSSFDrawing) {
                XSSFDrawing drawing = (XSSFDrawing) part;
                List<XSSFShape> shapes = drawing.getShapes();
                for (XSSFShape shape : shapes) {
                    XSSFPicture picture = (XSSFPicture) shape;
                    XSSFClientAnchor anchor = picture.getPreferredSize();
                    CTMarker marker = anchor.getFrom();
                    String key = marker.getRow() + "-" + marker.getCol();
                    map.put(key, picture.getPictureData());
                }
            }
        }
        return map;
    }

    /**
     * 获取表格的总行和总高
     * @param sheet
     * @return
     */
    private  int[] getColsOfTable(Sheet sheet) {

        int[] data = {0, 0};
        for(int i = sheet.getFirstRowNum(); i < sheet.getLastRowNum(); i ++) {
            if(null != sheet.getRow(i)) {
                data[0] = sheet.getRow(i).getLastCellNum();
                data[1] = sheet.getRow(i).getHeight();
            }else {
                continue;
            }
        }
        return data;
    }


    public static void main(String[] args) throws FileNotFoundException {
        File sourceFile = new File("C:\\Users\\ZHAOJIAN\\Desktop\\测试文件\\sa_task_template.xls");
        FileInputStream fis = new FileInputStream(sourceFile);
        System.out.println(new ExcelFilePreviewer().convert2Str(fis, "xls"));

        System.out.println("========================================================================================");

        File sourceFile2 = new File("C:\\Users\\ZHAOJIAN\\Desktop\\测试文件\\sa_task_template.xlsx");
        FileInputStream fis2 = new FileInputStream(sourceFile2);
        System.out.println(new ExcelFilePreviewer().convert2Str(fis2, "xlsx"));
    }
}
